#include "../include/preprocess.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 处理文件输入输出
void process_log_file(const char* input_filename, const char* output_filename) {
    printf("开始处理日志文件: %s -> %s\n", input_filename, output_filename);
    
    // 初始化预处理模块
    if (!preprocess_init()) {
        fprintf(stderr, "预处理模块初始化失败\n");
        exit(EXIT_FAILURE);
    }
    
    FILE* input_file = fopen(input_filename, "r");
    if (!input_file) {
        perror("无法打开输入文件");
        preprocess_cleanup();
        exit(EXIT_FAILURE);
    }
    
    FILE* output_file = fopen(output_filename, "w");
    if (!output_file) {
        perror("无法打开输出文件");
        fclose(input_file);
        preprocess_cleanup();
        exit(EXIT_FAILURE);
    }
    
    char line[4096];
    int line_count = 0;
    clock_t start_time = clock();
    
    printf("正在处理日志文件...\n");
    
    while (fgets(line, sizeof(line), input_file) != NULL) {
        line_count++;
        
        // 去除换行符
        size_t len = strlen(line);
        if (len > 0 && line[len-1] == '\n') {
            line[len-1] = '\0';
        }
        
        // 处理日志行
        char* processed = preprocess_log(line);
        if (processed) {
            fprintf(output_file, "%s\n", processed);
            free(processed);
        } else {
            fprintf(output_file, "%s\n", line);
        }
        
        if (line_count % 1000 == 0) {
            printf("已处理 %d 行...\n", line_count);
        }
    }
    
    clock_t end_time = clock();
    double elapsed_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
    
    printf("处理完成!\n");
    printf("统计信息:\n");
    printf("- 总行数: %d\n", line_count);
    printf("- 耗时: %.2f 秒\n", elapsed_time);
    printf("- 平均速度: %.2f 行/秒\n", line_count / elapsed_time);
    
    fclose(input_file);
    fclose(output_file);
    preprocess_cleanup();
}

int main(int argc, char* argv[]) {
    if (argc != 3) {
        printf("用法: %s 输入文件 输出文件\n", argv[0]);
        printf("示例: %s Linux_2k.log Linux_out.log\n", argv[0]);
        return EXIT_FAILURE;
    }
    
    process_log_file(argv[1], argv[2]);
    
    return EXIT_SUCCESS;
}